using GLib;

namespace Magicom
{
    public interface ControllerBehavior : GLib.Object
    {
        public abstract string[] port_enum();
        public abstract void port_change(string port_name);
        public abstract bool port_open();
        public abstract void port_close();
        public abstract void port_send(string text, bool newline);
    }
    
    public abstract class BaseController : GLib.Object, ControllerBehavior
    {
        protected SerialPortClass port;
        
        public SerialPortObserver observer { get; construct set; }
        
        public BaseController(SerialPortObserver observer)
        {
            Object(observer : observer);
        }
        
        public virtual string[] port_enum()
        {            
            return SerialPortClass.@enum();
        }
        
        public virtual void port_change(string port_name)
        {
            port = new SerialPortClass(port_name);
        }
        
        public virtual bool port_open()
        {
            if(true == port.open())
            {
               port.register_observer(observer); 
               return true;
            }
            
            return false;
        }
        
        public virtual void port_close()
        {
            port.unregister_observer(observer); 
            
            port.close();
        }
        
        public virtual void port_send(string text, bool newline)
		{
			port.write((text + (newline ? "\r\n" : "")).data);
		}
    }
    
    public class Controller : BaseController
    {        
        public Controller(SerialPortObserver observer)
        {
            base(observer);
        }
    }
}
